package com.usoft;

import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import akka.dispatch.OnComplete;
import scala.concurrent.ExecutionContextExecutorService;
import scala.concurrent.Future;

import java.util.concurrent.Executors;

/**
 * Created by liyanxin on 2015/1/9.
 */
public class FutureAddThen2 {

    /**
     * 使用addThen 实现这样一个功能，连接两个字符串，然后使用addAThen得到
     * 最后字符串的长度
     *
     * @param args
     */
    public static void main(String args[]) {
        final ExecutionContextExecutorService ec = ExecutionContexts.
                fromExecutorService(Executors.newCachedThreadPool());

        final Future<String> f1 = Futures.successful("com.hello ");
        final Future<String> f2 = Futures.successful("world");

        Future<String> f3 = f1.flatMap(new Mapper<String, Future<String>>() {
            @Override
            public Future<String> apply(final String s) {
                return f2.map(new Mapper<String, String>() {
                    @Override
                    public String apply(final String t) {
                        return s + t;
                    }
                }, ec);
            }
        }, ec);

        Future<String> result = f3.andThen(new OnComplete<String>() {
            @Override
            public void onComplete(Throwable failure, String success) throws Throwable {
                if (failure != null) {
                    failure.printStackTrace();
                } else {
                    System.out.println(success);
                }
            }
        }, ec);
    }

}
